<template>
  <!--图片列表弹窗-->
  <el-dialog v-model="pd.imgListShow" :title="pd.title" width="778px" @close="getBack">
    <el-row :gutter="20" style="margin-bottom: 15px;">
      <el-col :span="6">
        <el-input clearable v-model="pd.queryParams.fileName" placeholder="请输入图片名称" prefix-icon="Search" />
      </el-col>
      <el-col :span="2" style="margin-left: 8px;">
        <el-button type="primary" @click="getList">查询</el-button>
      </el-col>
      <el-col :span="3" style="margin-left: 8px;">
        <el-button type="primary" @click="handleReset">重置</el-button>
      </el-col>
    </el-row>
    <el-row :gutter="20">

      <el-col :span="18">
        <el-upload
           action="#"
           :file-list="pd.urls"
           list-type="picture-card"
           class="listImg"
           :on-exceed="handleExceed"
           :on-error="handleUploadError"
           :on-change="handleUpload"
           :auto-upload="false"
        >
          <el-icon style="width: 100%; height: 100%;">
            <Plus />
          </el-icon>
          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" style="width: 100px;height: 100px;" :src="file.url" alt="图片" />
              <span class="text">{{ file.fileName }}</span>
              <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-delete" v-if="!file.check && props.limit"
                  @click="handleAddCheck(file)">
              <el-icon>
                <Check />
              </el-icon>
            </span>
            <span class="el-upload-list__item-delete" v-if="file.check && props.limit"
                  @click="handleAddCheck(file)">
              <el-icon>
                <Close />
              </el-icon>
            </span>
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
              <el-icon><zoom-in /></el-icon>
            </span>
            <span class="el-upload-list__item-delete" @click="handleDelete(file)">
              <el-icon>
                <Delete />
              </el-icon>
            </span>
          </span>
            </div>
            <div class="rightCheck" v-show="file.check">
              <el-icon>
                <Check />
              </el-icon>
            </div>
          </template>

          <template #tip>
            <div class="el-upload__tip">
              请上传
              <template v-if="fileSize">
                大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
              </template>
              <template v-if="type">
                格式为 <b style="color: #f56c6c">{{ type.join("/") }}</b>
              </template>
              的文件
              <template v-if="limit">
                还剩余 <b style="color: #f56c6c">{{ residueNum }}个</b> 可选择
              </template>
            </div>
          </template>
        </el-upload>
      </el-col>
    </el-row>
    <el-row>
      <pagination v-show="pd.total > 0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                  v-model:limit="pd.queryParams.pageSize" @pagination="getList" :page-sizes="[14, 28]" />
    </el-row>
    <template #footer>
  <span class="dialog-footer">
    <el-button type="primary" @click="emit('ok', pd.fileList)">确定</el-button>
    <el-button @click="getBack">取消</el-button>
  </span>
    </template>
  </el-dialog>

  <!--切图弹窗-->
  <imgCut
    :cutout-show="pd.cutoutShow"
    :img-file="pd.fileBack"
    @ok="handleCropperClose"
  />

  <el-dialog v-model="pd.imgShow" width="500px">
    <el-image :src="pd.dialogImageUrl" fit="fill" />
  </el-dialog>

</template>

<script setup name="PictureList" lang="ts">

import {Check, Close, Delete, Plus, ZoomIn} from '@element-plus/icons-vue'
import "vue-cropper/dist/index.css";
import { getCurrentInstance, reactive } from "vue";
import {delOss, listOss, OssQuery} from "@/views/system/oss/api";
import imgCut from "@/views/system/oss/picture.vue";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emit = defineEmits(["ok"]);
const props = defineProps({
  idList: [String, Number],
  //file
  imgFile: {
    type: Object,
    default: [],
  },
  // 数量限制
  limit: {
    type: Number,
    default: 1,
  },
  // 样式
  styleType: {
    type: Boolean,
    default: true,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  type: {
    type: Array,
    default: () => ["png", "jpg", "jpeg"],
  },
  // 显示列表弹窗
  showList: {
    type: Boolean,
    default: false
  },
})

const residueNum = computed(
  () => props.limit - pd.fileList.length
);

const pd = reactive({
  title: "图片列表",
  imgListShow: false,// 图片列表弹窗
  imgShow: false,// 图片详情弹窗
  cutoutShow: false,// 切图弹窗
  dialogImageUrl: '',
  fileList: [] as any,//勾选图片数组
  fileBack: [] as any,
  urls: [] as any,//图片列表数组
  uploadLimit: 5,
  total: 0,
  queryParams: <OssQuery>{
    pageNum: 1,
    pageSize: 14,
    url: null,
    type: null,
    updateTime: null,
  },
})

watch(() => props.showList, val => {
  pd.imgListShow = val;
  pd.fileList = JSON.parse(JSON.stringify(props.imgFile));
  getList();
}, { deep: true, immediate: true });

// 关闭切图窗口
function handleCropperClose(value: any) {
  console.log(value)
  pd.cutoutShow = false;
  getList()
}
// 刷新图片列表
function handleReset() {
  pd.queryParams = {
    pageNum: 1,
    pageSize: 14,
  }
  getList()
}
// 是否勾选图片
function handleAddCheck(file: any) {
  if (file.check) {
    file.check = false
    pd.fileList = pd.fileList.filter((item: any) => {
      return item.ossId != file.ossId
    })
  } else {
    if (pd.fileList.length + 1 > props.limit) {
      return proxy?.$modal.msgError("选择上限");
    }
    file.check = true
    pd.fileList.push(file)
  }
}

// 是否查看大图
function handlePictureCardPreview(uploadFile: any){
  pd.dialogImageUrl = uploadFile.url
  pd.imgShow = true
}

//退出
function getBack(){
  pd.fileList = []
  pd.urls = []
  emit('ok', [false])
}

// 文件删除
async function handleDelete(uploadFile: any) {
  let ossIdFile = pd.fileList.filter((item:any) => {
    return item.url == uploadFile.url
  })
  if (ossIdFile.length == 0 && pd.urls.length > 0){
    ossIdFile = pd.urls.filter((item:any) => {
      return item.url == uploadFile.url
    })
  }
  proxy?.$modal.confirm('是否确认删除？').then(() => {
    return delOss(ossIdFile[0].ossId)
  }).then(() => {
    proxy?.$modal.msgSuccess("删除成功");
    getList()
  });
}

// 文件个数超出
function handleExceed() {
  proxy?.$modal.msgError(`上传文件数量不能超过 ${pd.uploadLimit} 个!`);
}

// 上传失败
function handleUploadError() {
  proxy?.$modal.msgError("上传文件失败");
  proxy?.$modal.closeLoading();
}

//添加文件
async function handleUpload(uploadFile: UploadFile) {
  if (!props.showList) pd.fileList = []
  pd.fileBack = uploadFile.raw;
  let size = pd.fileBack.size / 1024 / 1024
  if (pd.fileBack.type.indexOf("image/") == -1) {
    proxy?.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
    return false;
  } else if (props.fileSize && size > props.fileSize) {
    proxy?.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
    return false;
  }
  pd.cutoutShow = true
}

/** 初始化数据 */
function getList() {
  listOss(pd.queryParams).then((res) => {
    if (res.rows.length > 0) {
      let resUrls = res.rows as any
      resUrls = resUrls.filter((item: any)=>{
        return (".png.jpg.jpeg").includes(item.fileSuffix)
      })
      pd.total = res.total
      resUrls.forEach((item: any) => {
        item.check = false
      })
      if (props.showList && pd.fileList.length > 0) {
        pd.fileList.forEach((element: any) => [
          resUrls.forEach((item: any) => {
            if (item.ossId == element.ossId) {
              item.check = true
            }
          })
        ])
      }
      pd.urls = resUrls
    } else {
      pd.urls = []
    }
  })
}
</script>

<style lang="scss" scoped>

.listImg {
  margin-left: 8px;
}

.rightCheck {
  right: -15px;
  top: -6px;
  width: 40px;
  height: 24px;
  background: var(--el-color-success);
  text-align: center;
  transform: rotate(45deg);
  position: absolute;

  i {
    color: #fff;
    font-size: 12px;
    margin-top: 11px;
    transform: rotate(-45deg);
  }
}
</style>
<!-- 覆盖elementUI样式 -->
<style lang="scss">
.hide .el-upload--picture-card {
  display: none;
}

.head-container {
  text-align: center;
}

.listImg {
  .el-upload-list__item {
    width: 100px !important;
    height: 124px !important;

    .text {
      width: 100px;
      line-height: 20px;
      height: 20px;
      display: block;
      overflow: hidden;
      background: #f6f6f6;
      padding: 0 5px;
      text-align: center;
      position: absolute;
      bottom: -2px;
    }
  }

  .el-upload--picture-card {
    width: 100px !important;
    height: 124px !important;
  }
}

.uploadImg {
  .el-upload-list__item {
    width: 90px !important;
    height: 90px !important;
  }

  .el-upload--picture-card {
    width: 90px !important;
    height: 90px !important;
  }
}
</style>
